package com.xindaoapp.happypet.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.MessageDigest;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.client.CookieStore;
import org.apache.http.cookie.Cookie;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;
import android.media.ExifInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ImageSpan;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;
import cn.jpush.android.api.JPushInterface;

import com.alibaba.fastjson.JSON;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.bitmap.BitmapDisplayConfig;
import com.lidroid.xutils.bitmap.callback.BitmapLoadCallBack;
import com.lidroid.xutils.bitmap.callback.BitmapLoadFrom;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.Animator.AnimatorListener;
import com.nineoldandroids.animation.AnimatorSet;
import com.nineoldandroids.animation.ObjectAnimator;
import com.rockerhieu.emojicon.EmojiParser;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.bean.SocializeEntity;
import com.umeng.socialize.controller.listener.SocializeListeners.SocializeClientListener;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.XDHttpClient;
import com.xindaoapp.happypet.alipy.Base64;
import com.xindaoapp.happypet.api.AddClient;
import com.xindaoapp.happypet.api.Address;
import com.xindaoapp.happypet.application.HappyPetApplication;
import com.xindaoapp.happypet.bean.MainZuixinData;
import com.xindaoapp.happypet.bean.UpdateInfo;
import com.xindaoapp.happypet.bean.User;
import com.xindaoapp.happypet.bean.UserInfo;
import com.xindaoapp.happypet.ui.ViewWrapper2;
import com.xindaoapp.happypet.utils.CommonParameter.UserState;
import com.xindaoapp.happypet.view.HelpPopupWindow;

public class CommonUtil {

    /**
     * 尾巴数目会改变的操作，会刷新尾巴
     * 
     * @param context
     */
    public static void refurshWeiba(final Context context) {
        RequestParams params = new RequestParams();
        params.put("uid", UserState.getUserUid());
        AddClient.get(Address.GETUSERINFOBYUID, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, String content) {
                try {
                    UserInfo parse = JSON.parseObject(content, UserInfo.class);
                    // UserState.setUser(parse.userinfo);
                    UserState.getUser().niuniu = parse.userinfo.niuniu;
                    context.sendBroadcast(new Intent(Constants.ACTION_WEIBA_COUNT_CHANGED));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                super.onSuccess(statusCode, content);
            }

            @Override
            public void onFailure(Throwable error, String content) {
                super.onFailure(error, content);
            }
        });
    }

    public static void showDialog2(Context context, String str) {
        View layout = View.inflate(context, R.layout.dialog_one, null);
        if (str.indexOf("尾巴") >= 0) {
            layout.setBackgroundResource(R.drawable.addscore);
        } else {
            layout.setBackgroundResource(R.drawable.ic_dialog_bg_jifentishi);
        }
        TextView title = (TextView) layout.findViewById(R.id.add_score);
        title.setText(str);
        Toast toast = new Toast(context);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.setDuration(Toast.LENGTH_SHORT);
        toast.setView(layout);
        toast.show();
    }

    private final static long ONEMINUTE = 60 * 1000;

    /**
     * 格式化时间，格式为yyyy-MM-dd
     * 
     * @param time
     * @return
     */
    public static String formatTime2(String time) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd");
        try {
            java.util.Date date = df.parse(time);
            long spacing = System.currentTimeMillis() - date.getTime();
            if (spacing < 10 * ONEMINUTE) {
                return "刚刚";
            } else if (spacing < 60 * ONEMINUTE) {
                return spacing / (ONEMINUTE) + "分钟前";
            } else if (spacing < 24 * 60 * ONEMINUTE) {
                return spacing / (60 * ONEMINUTE) + "小时前";
            } else if (spacing < 48 * 60 * ONEMINUTE) {
                return "一天前";
            } else {
                return df2.format(date);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "null";
    }

    /**
     * 格式化时间-11-11 (列表) 不到一分钟 ，显示“刚刚”； 大于一分钟 小于60分 显示几分钟前； 今年，显示月日； 其他年，显示年月日
     * 
     * @param time
     * @return
     */
    public static String formatTimeForListCommon(String time) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat df3 = new SimpleDateFormat("yyyy");
        SimpleDateFormat df4 = new SimpleDateFormat("MM-dd");

        try {
            java.util.Date date = df.parse(time);
            long spacing = System.currentTimeMillis() - date.getTime();
            if (!df3.format(date).equals(df3.format(new Date()))) {
                return df2.format(date);
            } else if (spacing < 1 * ONEMINUTE) {
                return "刚刚";
            } else if (spacing < 60 * ONEMINUTE) {
                return spacing / (ONEMINUTE) + "分钟前";
            } else {
                return df4.format(date);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String formatTimeForListCommonForDaShang(String time) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat df3 = new SimpleDateFormat("yyyy");
        SimpleDateFormat df4 = new SimpleDateFormat("MM-dd");

        try {
            java.util.Date date = df.parse(time);
            long spacing = System.currentTimeMillis() - date.getTime();
            if (!df3.format(date).equals(df3.format(new Date()))) {
                return df2.format(date);
            } else if (spacing < 1 * ONEMINUTE) {
                return "刚刚";
            } else if (spacing < 60 * ONEMINUTE) {
                return spacing / (ONEMINUTE) + "分钟前";
            } else {
                return df4.format(date);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 格式化时间-11-11 (帖子详情) 今年，显示月日时分； 其他年，显示年月日
     * 
     * @param time
     * @return
     */
    public static String formatTimeForDetailCommon(String time) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat df5 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat df3 = new SimpleDateFormat("yyyy");
        SimpleDateFormat df4 = new SimpleDateFormat("MM-dd HH:mm");

        try {
            java.util.Date date = df.parse(time);
            long spacing = System.currentTimeMillis() - date.getTime();
            if (!df3.format(date).equals(df3.format(new Date()))) {
                return df5.format(date);
            } else {
                return df4.format(date);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String formatTimeForQiandao(String time) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd");

        try {
            java.util.Date date = df.parse(time);
            return df2.format(date);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return time;
    }

    public static String formatTime(String time) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat df2 = new SimpleDateFormat("MM-dd");
        try {
            java.util.Date date = df.parse(time);
            long spacing = System.currentTimeMillis() - date.getTime();

            if (spacing < 10 * ONEMINUTE) {
                return "刚刚";
            } else if (spacing < 60 * ONEMINUTE) {
                return spacing / (ONEMINUTE) + "分钟前";
            } else if (spacing < 24 * 60 * ONEMINUTE) {
                return spacing / (60 * ONEMINUTE) + "小时前";
            } else if (spacing < 48 * 60 * ONEMINUTE) {
                return "一天前";
            } else {
                // return (String.valueOf(date.getMonth()).length() == 1 ? "0" + date.getMonth()
                // : date.getMonth())
                // + "-"
                // + (String.valueOf(date.getDay()).length() == 1 ? "0" + date.getDay() : date
                // .getDay());
                return df2.format(date);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "null";
    }

    public static String formatTimeForZuixin(String time) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat df4 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat df5 = new SimpleDateFormat("yyyy");
        SimpleDateFormat df2 = new SimpleDateFormat("MM-dd");
        SimpleDateFormat df3 = new SimpleDateFormat("HH:mm");
        try {
            java.util.Date date = df.parse(time);
            long spacing = System.currentTimeMillis() - date.getTime();

            if (!df5.format(date).equals(df5.format(new Date()))) {
                return df4.format(date);
            } else if (spacing < 1 * ONEMINUTE) {
                return "刚刚";
            } else if (spacing < 60 * ONEMINUTE) {
                return spacing / (ONEMINUTE) + "分钟前";
            } else if (spacing < 24 * 60 * ONEMINUTE) {
                return df3.format(date);
            } else {
                return df2.format(date);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String formatTimeForZanList(String time) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat df3 = new SimpleDateFormat("yyyy");
        SimpleDateFormat df4 = new SimpleDateFormat("MM-dd");
        SimpleDateFormat df5 = new SimpleDateFormat("HH:mm");
        try {
            java.util.Date date = df.parse(time);
            long spacing = System.currentTimeMillis() - date.getTime();

            if (spacing < 1 * ONEMINUTE) {
                return "刚刚";
            } else if (spacing < 60 * ONEMINUTE) {
                return spacing / (ONEMINUTE) + "分钟前";
            } else if (spacing < 24 * 60 * ONEMINUTE) {
                return spacing / (60 * ONEMINUTE) + "小时前";
            } else {
                return df2.format(date);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }

    public static String formatTimeForFreeUse(long time) {
        try {
            long spacing = time - System.currentTimeMillis();

            if (spacing <= 0) {
                return "0";
            } else if (spacing < ONEMINUTE) {
                return "不到1分钟";
            } else if (spacing < 60 * ONEMINUTE) {
                return spacing / (ONEMINUTE) + "分钟";
            } else if (spacing < 24 * 60 * ONEMINUTE) {
                return spacing / (60 * ONEMINUTE) + "小时";
            } else {
                return spacing / (24 * 60 * ONEMINUTE) + "天";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "null";
    }

    public static String getVersionName(Context context) {
        try {
            return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return "1";
    }

    /**
     * 检查更新
     * 
     * @param activity
     */
    public static void checkUpdate(final Activity activity) {
        HappyPetApplication.get().getMoccaApi()
                .checkUpdate(getVersionName(activity), new IRequest<UpdateInfo>() {
                    @Override
                    public void request(final UpdateInfo t) {
                        if (t == null) {
                            return;
                        }
                        if (t.needup.equals("1")) {
                            String force = t.force; // 判断是否强制更新
                            boolean flag_force = true;
                            if (force.equals("1")) {
                                flag_force = false;
                            } else {
                                flag_force = true;
                            }
                            if (null != t) {
                                switch (String.valueOf(getVersionCode(activity)).compareTo(
                                        t.version)) {
                                    case 0: // 版本一致,不更新

                                        break;
                                    case 1: // 当前版本更大,不更新

                                        break;
                                    default: // 低版本，更新
                                        // 加入红点提示
                                        SharePrefUtil.saveBoolean(activity, "updatenew", true);
                                        if (flag_force) {
                                            new AlertDialog.Builder(activity)
                                                    .setTitle("版本升级")
                                                    .setMessage(t.content)
                                                    .setNegativeButton("立即更新",
                                                            new DialogInterface.OnClickListener() {
                                                                @Override
                                                                public void onClick(
                                                                        DialogInterface dialog,
                                                                        int which) {
                                                                    CommonUtil.startWebView(
                                                                            activity, t.url);
                                                                }
                                                            })
                                                    .setPositiveButton("忽略本次",
                                                            new DialogInterface.OnClickListener() {

                                                                @Override
                                                                public void onClick(
                                                                        DialogInterface dialog,
                                                                        int which) {

                                                                }
                                                            }).create().show();
                                        } else {
                                            Builder alertDialog = new AlertDialog.Builder(activity);
                                            alertDialog
                                                    .setTitle("版本升级")
                                                    .setMessage(t.content)
                                                    .setCancelable(false)
                                                    .setNegativeButton("立即更新",
                                                            new DialogInterface.OnClickListener() {
                                                                @Override
                                                                public void onClick(
                                                                        DialogInterface dialog,
                                                                        int which) {
                                                                    CommonUtil.startWebView(
                                                                            activity, t.url);
                                                                    System.exit(0);
                                                                }
                                                            }).create().show();
                                            alertDialog
                                                    .setOnKeyListener(new DialogInterface.OnKeyListener() {
                                                        @Override
                                                        public boolean onKey(
                                                                DialogInterface dialog,
                                                                int keyCode, KeyEvent event) {
                                                            if (keyCode == KeyEvent.KEYCODE_BACK) {
                                                                return true;
                                                            } else {
                                                                return false; // 默认返回 false
                                                            }
                                                        }
                                                    });
                                        }
                                        break;
                                }
                            }
                        } else {
                            // 去掉红点提示
                            SharePrefUtil.saveBoolean(activity, "updatenew", false);
                        }
                    }
                });
    }

    /**
     * 将EmojiParser解析出的"[e]xxxxx[/e]"代码，渲染成图片
     * 
     * @param content
     * @param mContext
     * @return
     */
    public static SpannableStringBuilder convetToHtml(String content, Context mContext) {
        String regex = "\\[e\\](.*?)\\[/e\\]";
        Pattern pattern = Pattern.compile(regex);
        String emo = "";
        Resources resources = mContext.getResources();
        String unicode =
                com.rockerhieu.emojicon.parse.EmojiParser.getInstance(mContext).parseEmoji(content);
        Matcher matcher = pattern.matcher(unicode);
        SpannableStringBuilder sBuilder = new SpannableStringBuilder(unicode);
        Drawable drawable = null;
        ImageSpan span = null;
        while (matcher.find()) {
            emo = matcher.group();
            try {
                int id = 0;
                if (emo.contains("YangCongTou")) {
                    id =
                            resources.getIdentifier(
                                    "f"
                                            + emo.substring(
                                                    emo.indexOf("]") + "YangCongTou".length() + 1,
                                                    emo.lastIndexOf("[")), "drawable",
                                    mContext.getPackageName());
                } else {
                    id =
                            resources.getIdentifier(
                                    "emoji_"
                                            + emo.substring(emo.indexOf("]") + 1,
                                                    emo.lastIndexOf("[")), "drawable",
                                    mContext.getPackageName());
                }
                if (id != 0) {
                    drawable = resources.getDrawable(id);
                    drawable.setBounds(0, 0, CommonUtil.dip2px(mContext, 25),
                            CommonUtil.dip2px(mContext, 25));
                    span = new ImageSpan(drawable);
                    sBuilder.setSpan(span, matcher.start(), matcher.end(),
                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
            } catch (Exception e) {
                break;
            }
        }
        return sBuilder;
    }

    public static void saveUserInfo(User user) {
        MoccaPreferences.UserInfo.put(CommonUtil.stringToObj(user));
        MoccaPreferences.Logged.put(true);
        CookieStore cookieStore = AddClient.getClient().getCookie();

        ArrayList<HashMap<String, Object>> temp = new ArrayList<HashMap<String, Object>>();

        StringBuffer sb = new StringBuffer();

        for (int i = 0; i < cookieStore.getCookies().size(); i++) {
            Cookie cookie = cookieStore.getCookies().get(i);
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("version", String.valueOf(cookie.getVersion()));
            map.put("name", cookie.getName());
            map.put("value", cookie.getValue());
            map.put("domain", cookie.getDomain());
            map.put("path", cookie.getPath());
            map.put("expiry", cookie.getExpiryDate());
            sb.append(cookie.getName());
            temp.add(map);
        }

        MoccaPreferences.CookieData.put(CommonUtil.stringToObj(temp));
    }

    /**
     * 将对象进行base64编码
     * 
     * @param context
     * @param key
     * @param object
     */
    public static String stringToObj(Object object) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(baos);
            oos.writeObject(object);
            // 将对象的转为base64码
            return new String(org.apache.commons.codec.binary.Base64.encodeBase64(baos
                    .toByteArray())).toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 将String经过base64编码的对象读取出来
     * 
     * @param context
     * @param key
     * @param defValue
     * @return
     */
    public static Object objToString(String objBase64) {
        // 对Base64格式的字符串进行解码
        byte[] base64Bytes =
                org.apache.commons.codec.binary.Base64.decodeBase64(objBase64.getBytes());
        ByteArrayInputStream bais = new ByteArrayInputStream(base64Bytes);

        ObjectInputStream ois;
        Object obj = null;
        try {
            ois = new ObjectInputStream(bais);
            obj = ois.readObject();
            ois.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return obj;
    }

    public static void registerJpush(Context context, String tag) {
        // if (JPushInterface.isPushStopped(context)) {
        JPushInterface.resumePush(context);
        // }
        Set<String> set = new HashSet<String>();
        set.add(tag);
        JPushInterface.setTags(context, set, null);
    }

    public static int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    /**
     * 压缩图片
     * 
     * @param file
     * 
     * @return 文件大于100K，进行压缩
     */
    public static File compressImage(String filePath) {
        File file = new File(filePath);
        /** -----start------ */
        if (file.length() >= 150 * 1024) {
            CommonUtil.mkFiledir(Environment.getExternalStorageDirectory().getAbsolutePath()
                    + "/happypet/thumbnail");
            String path =
                    Environment.getExternalStorageDirectory().getAbsolutePath()
                            + "/happypet/thumbnail" + File.separator + System.currentTimeMillis()
                            + ".jpg";
            try {
                CommonUtil.compressImage(file.getAbsolutePath(), path);
            } catch (Exception e) {
                e.printStackTrace();
            }
            file = new File(path);// 将之前的文件替换为新的文件
        }
        /** -----end------ */
        // if (file.length() >= 100 * 1024) {// 文件大于500K，进行压缩
        // CommonUtil.mkFiledir(Environment.getExternalStorageDirectory().getAbsolutePath()
        // + "/happypet/thumbnail");
        // String path =
        // Environment.getExternalStorageDirectory().getAbsolutePath()
        // + "/happypet/thumbnail" + File.separator + System.currentTimeMillis()
        // + ".jpg";
        // try {
        // CommonUtil.compressImage(file.getAbsolutePath(), path);
        // } catch (Exception e) {
        // e.printStackTrace();
        // }
        // file = new File(path);// 将之前的文件替换为新的文件
        // }
        return file;
    }

    /**
     * 创建文件目录
     * 
     * @param filePath
     * @return
     */
    public static boolean mkFiledir(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            return file.mkdirs();
        }
        return false;
    }

    public static String decode(String str) {
        return Base64.encode(Base64.encode(str.getBytes()).getBytes());
    }


    public static String transitionToFloat(Float str) {
        DecimalFormat decimalFormat = new DecimalFormat("0.00");// 构造方法的字符格式这里如果小数不足2位,会以0补足.
        return decimalFormat.format(str);// format 返回的是字符串
        // return new BigDecimal(str).setScale(2, 4).floatValue();
    }

    public static void scalePicture(String filename, int width, int height) {
        try {
            BitmapFactory.Options opts = new BitmapFactory.Options();
            Bitmap bitmap = BitmapFactory.decodeFile(filename, opts);

            Matrix m = new Matrix();
            // m.setRotate(90); // 旋转angle度
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, m, true);// 从新生成图片

            File file = new File(filename);
            try {
                FileOutputStream out = new FileOutputStream(file);
                if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)) {
                    out.flush();
                    out.close();
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static void compressImage(String srcPath, String targetFileName) {
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        // 开始读入图片，此时把options.inJustDecodeBounds 设回true了
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);// 此时返回bm为空

        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        // 现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
        float hh = 1280f;// 这里设置高度为1280f
        float ww = 1280f;// 这里设置宽度为720f
        // float hh = 1280f;// 这里设置高度为800f
        // float ww = 1280f;// 这里设置宽度为480f
        // 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = 1;// be=1表示不缩放
        /** 往上取 */
        // if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
        // be = (int) Math.ceil((newOpts.outWidth / ww));
        // } else if (w <= h && h > hh) {// 如果高度高的话根据宽度固定大小缩放
        // be = (int) Math.ceil((newOpts.outHeight / hh));
        // }
        /** 四舍五入 */
        if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
            be = (int) (newOpts.outWidth / ww + 0.5f);
        } else if (w < h && h > hh) {// 如果高度高的话根据宽度固定大小缩放
            be = (int) (newOpts.outHeight / hh + 0.5f);
        }
        if (be <= 0) {
            be = 1;
        }
        // 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
        while (true) {
            System.out.println("sample size：" + be);
            newOpts.inSampleSize = be;// 设置缩放比例
            try {
                bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
                bitmap = compressImage(bitmap);// 压缩好比例大小后再进行质量压缩
                break;
            } catch (OutOfMemoryError e) {// 如果解析错误，则对处理压缩比例处理
                System.out.println("重绘1...");
                e.printStackTrace();
                be++;
            }
        }

        Matrix m = new Matrix();
        m.setRotate(readPictureDegree(srcPath)); // 旋转angle度
        bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), m, true);// 从新生成图片

        File file = new File(targetFileName);

        try {
            FileOutputStream out = new FileOutputStream(file);
            if (bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out)) {
                out.flush();
                out.close();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static Bitmap compressImage(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while (baos.toByteArray().length / 1024 > 150 && options > 0) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset();// 重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;// 每次都减少10

        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
        BitmapFactory.Options opts = new BitmapFactory.Options();
        // opts.inSampleSize = 1;
        Bitmap bitmap = null;
        // while (true) {
        // try {
        bitmap = BitmapFactory.decodeStream(isBm, null, opts);// 把ByteArrayInputStream数据生成图片
        // break;
        // } catch (OutOfMemoryError e) {
        // System.out.println("重绘...");
        // opts.inSampleSize += 1;
        // isBm = new ByteArrayInputStream(baos.toByteArray());
        // e.printStackTrace();
        // }
        // }
        return bitmap;
    }

    /**
     * 读取图片属性：旋转的角度
     * 
     * @param path 图片绝对路径
     * @return degree旋转的角度
     */
    public static int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation =
                    exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                            ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return degree;
        }
        return degree;
    }

    public static void scalePicture(String LocalFileName, String targetFileName, int width,
            int height) {
        try {
            BitmapFactory.Options opts = new BitmapFactory.Options();
            Bitmap bitmap = BitmapFactory.decodeFile(LocalFileName, opts);

            Matrix m = new Matrix();
            // m.setRotate(90); // 旋转angle度
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, m, true);// 从新生成图片

            File file = new File(targetFileName);
            try {
                FileOutputStream out = new FileOutputStream(file);
                if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)) {
                    out.flush();
                    out.close();
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static int getVersionCode(Activity context) {
        try {
            return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return -1;
    }

    public static void startWebView(Context context, String url) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(url));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    public static void showInfoDialog(Context context, String message) {
        showInfoDialog(context, message, "提示", "确定", null);
    }

    /*
     * public static void a(Context context) { BitmapFactory.Options options = new
     * BitmapFactory.Options(); options.inSampleSize = 2;// 图片宽高都为原来的二分之一，即图片为原来的四分之一 Bitmap b =
     * BitmapFactory.decodeResource(context.getResources(), R.drawable.bootimage_logo, options); }
     */

    public static void showInfoDialog(Context context, String message, String titleStr,
            String positiveStr, DialogInterface.OnClickListener onClickListener) {
        AlertDialog.Builder localBuilder = new AlertDialog.Builder(context);
        localBuilder.setTitle(titleStr);
        localBuilder.setMessage(message);
        if (onClickListener == null)
            onClickListener = new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            };
        localBuilder.setPositiveButton(positiveStr, onClickListener);
        localBuilder.show();
    }

    public static String md5(String paramString) {
        String returnStr;
        try {
            MessageDigest localMessageDigest = MessageDigest.getInstance("MD5");
            localMessageDigest.update(paramString.getBytes());
            returnStr = byteToHexString(localMessageDigest.digest());
            return returnStr;
        } catch (Exception e) {
            return paramString;
        }
    }

    /**
     * 将指定byte数组转换成16进制字符串
     * 
     * @param b
     * @return
     */
    public static String byteToHexString(byte[] b) {
        StringBuffer hexString = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            String hex = Integer.toHexString(b[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            hexString.append(hex.toUpperCase());
        }
        return hexString.toString();
    }

    /**
     * 判断当前是否有可用的网络以及网络类型 0：无网络 1：WIFI 2：CMWAP 3：CMNET
     * 
     * @param context
     * @return
     */
    public static int isNetworkAvailable(Context context) {
        ConnectivityManager connectivity =
                (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity == null) {
            return 0;
        } else {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        NetworkInfo netWorkInfo = info[i];
                        if (netWorkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                            return 1;
                        } else if (netWorkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                            String extraInfo = netWorkInfo.getExtraInfo();
                            if ("cmwap".equalsIgnoreCase(extraInfo)
                                    || "cmwap:gsm".equalsIgnoreCase(extraInfo)) {
                                return 2;
                            }
                            return 3;
                        }
                    }
                }
            }
        }
        return 0;
    }


    /**
     * 获取现在时间
     * 
     * @return 返回短时间字符串格式yyyy-MM-dd HH:mm:ss
     */

    public static String getStringDate() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(currentTime);
        return dateString;
    }

    /** 根据手机的分辨率从 dp 的单位 转成为 px(像素) */
    public static int dp2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /** 根据手机的分辨率从 px(像素) 的单位 转成为 dp */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public static int getScreenPicHeight(int screenWidth, Bitmap bitmap) {
        int picWidth = bitmap.getWidth();
        int picHeight = bitmap.getHeight();
        int picScreenHeight = 0;
        picScreenHeight = (screenWidth * picHeight) / picWidth;
        return picScreenHeight;
    }

    /**
     * @param context
     * @param button
     * @param nornalImageFileName
     * @param pressedImageFileName
     * @throws Exception
     */
    public static void bindViewSelector(Context context, final View view, String nornalImageurl,
            final String pressedImageUrl) {
        final StateListDrawable stateListDrawable = new StateListDrawable();
        final BitmapUtils utils = new BitmapUtils(context);
        utils.display(view, nornalImageurl, new BitmapLoadCallBack<View>() {

            @Override
            public void onLoadCompleted(View container, String uri, Bitmap bitmap,
                    BitmapDisplayConfig config, BitmapLoadFrom from) {
                Drawable normalDrawable = new BitmapDrawable(bitmap);
                stateListDrawable.addState(new int[] {android.R.attr.state_active}, normalDrawable);
                stateListDrawable.addState(new int[] {android.R.attr.state_focused,
                        android.R.attr.state_enabled}, normalDrawable);
                stateListDrawable
                        .addState(new int[] {android.R.attr.state_enabled}, normalDrawable);
                utils.display(container, pressedImageUrl, new BitmapLoadCallBack<View>() {

                    @Override
                    public void onLoadCompleted(View container, String uri, Bitmap bitmap,
                            BitmapDisplayConfig config, BitmapLoadFrom from) {
                        stateListDrawable.addState(new int[] {android.R.attr.state_pressed,
                                android.R.attr.state_enabled}, new BitmapDrawable(bitmap));

                        view.setBackgroundDrawable(stateListDrawable);

                    }

                    @Override
                    public void onLoadFailed(View container, String uri, Drawable drawable) {
                        // TODO Auto-generated method stub

                    }
                });
            }

            @Override
            public void onLoadFailed(View container, String uri, Drawable drawable) {

            }
        });

    }

    private static Drawable createDrawable(Drawable d, Paint p) {

        BitmapDrawable bd = (BitmapDrawable) d;
        Bitmap b = bd.getBitmap();
        Bitmap bitmap =
                Bitmap.createBitmap(bd.getIntrinsicWidth(), bd.getIntrinsicHeight(),
                        Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawBitmap(b, 0, 0, p); // 关键代码，使用新的Paint画原图，

        return new BitmapDrawable(bitmap);
    }

    /** 设置Selector。 本次只增加点击变暗的效果，注释的代码为更多的效果 */
    public static StateListDrawable createSLD(Context context, Drawable drawable) {
        StateListDrawable bg = new StateListDrawable();
        int brightness = 50 - 127;
        ColorMatrix cMatrix = new ColorMatrix();
        cMatrix.set(new float[] {1, 0, 0, 0, brightness, 0, 1, 0, 0, brightness,// 改变亮度
                0, 0, 1, 0, brightness, 0, 0, 0, 1, 0});

        Paint paint = new Paint();
        paint.setColorFilter(new ColorMatrixColorFilter(cMatrix));

        Drawable normal = drawable;
        Drawable pressed = createDrawable(drawable, paint);
        bg.addState(new int[] {android.R.attr.state_pressed,}, pressed);
        bg.addState(new int[] {android.R.attr.state_focused,}, pressed);
        bg.addState(new int[] {android.R.attr.state_selected}, pressed);
        bg.addState(new int[] {}, normal);
        return bg;
    }

    public static Bitmap getImageFromAssetsFile(Context ct, String fileName) {
        Bitmap image = null;
        AssetManager am = ct.getAssets();
        try {
            InputStream is = am.open(fileName);
            image = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return image;

    }

    @SuppressLint("NewApi")
    public static <Params, Progress, Result> void executeAsyncTask(
            AsyncTask<Params, Progress, Result> task, Params... params) {
        if (Build.VERSION.SDK_INT >= 11) {
            task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
        } else {
            task.execute(params);
        }
    }

    public static String getUploadtime(long created) {
        StringBuffer when = new StringBuffer();
        int difference_seconds;
        int difference_minutes;
        int difference_hours;
        int difference_days;
        int difference_months;
        long curTime = System.currentTimeMillis();
        difference_months = (int) (((curTime / 2592000) % 12) - ((created / 2592000) % 12));
        if (difference_months > 0) {
            when.append(difference_months + "月");
        }

        difference_days = (int) (((curTime / 86400) % 30) - ((created / 86400) % 30));
        if (difference_days > 0) {
            when.append(difference_days + "天");
        }

        difference_hours = (int) (((curTime / 3600) % 24) - ((created / 3600) % 24));
        if (difference_hours > 0) {
            when.append(difference_hours + "小时");
        }

        difference_minutes = (int) (((curTime / 60) % 60) - ((created / 60) % 60));
        if (difference_minutes > 0) {
            when.append(difference_minutes + "分钟");
        }

        difference_seconds = (int) ((curTime % 60) - (created % 60));
        if (difference_seconds > 0) {
            when.append(difference_seconds + "秒");
        }

        return when.append("前").toString();
    }

    public static boolean hasToken(Context ct) {
        String token = SharePrefUtil.getString(ct, "token", "");
        if (TextUtils.isEmpty(token)) {
            return false;
        } else {
            return true;
        }
    }

    public static void setListViewHeightBasedOnChildren(ListView listView) {
        // 获取ListView对应的Adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) { // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0); // 计算子项View 的宽高
            totalHeight += listItem.getMeasuredHeight(); // 统计所有子项的总高度
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }

    public static String formatDate() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        return sdf.format(new Date());
    }

    public static String formatPullToRefreshDate() {
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        return "今天   " + sdf.format(new Date());
    }



    public static boolean checkNetState(Context context) {
        boolean netstate = false;
        ConnectivityManager connectivity =
                (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        netstate = true;
                        break;
                    }
                }
            }
        }
        return netstate;
    }

    public static String formatTime(long time, boolean exactly) {
        if (exactly) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            return dateFormat.format(new Date(time));
        } else {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            return dateFormat.format(new Date(time));
        }
    }

    public static String formatTime2Date(long time) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return dateFormat.format(new Date(time));
    }

    public static String parseEmoji(String str) {
        // 判断字符串至少包含两个冒号:
        str = str + " ";
        int start = str.indexOf(":");
        if (str.indexOf(":", start + 1) >= 0) {
        } else {
            return str;
        }

        String[] split = str.split(":");
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < split.length; i++) {
            // if (!TextUtils.isEmpty(split[i])) {
            String string = EmojiParser.IEmojiMap.get(":" + split[i] + ":");
            String string2 = "";
            String string3 = "";
            if (i < split.length - 1) {
                string2 = EmojiParser.IEmojiMap.get(":" + split[i + 1] + ":");
                string3 = EmojiParser.IEmojiMap.get(":" + split[i + 1] + ":");
                if (TextUtils.isEmpty(string2)) {
                    string2 = split[i + 1];
                }
            }

            if (!TextUtils.isEmpty(string)) {
                String str1 = string.substring(1, string.length() - 1);
                sb.append("[e]" + str1 + "[/e]");
            } else if (split[i].contains("YangCongTou")) {
                sb.append("[e]" + split[i] + "[/e]");
            } else {
                if (i != split.length - 1) {
                    if (!string2.contains("YangCongTou") && TextUtils.isEmpty(string3)) {
                        sb.append(split[i] + ":");
                    } else {
                        sb.append(split[i]);
                    }
                } else {
                    sb.append(split[i]);
                }
            }
            // }
        }
        String s = sb.toString();
        return s;
    }

    public static String parseStr(String str) {

        if (TextUtils.isEmpty(str)) {
            return "";
        }

        while (str.contains("<img")) {
            int start = str.indexOf("<img");
            int end = str.indexOf("/>");
            if (end < 0) {
                break;
            }
            String temp = str.substring(start, end + "/>".length());

            int gifStart = temp.lastIndexOf(".gif");
            String name = temp.substring(gifStart - 2, gifStart);

            str = str.replace(temp, "{YangCongTou" + name + "}");
        }
        return str;
    }

    /**
     * @param str
     * @return 替换[] 成：
     */
    public static String replaceAllKuoHao(String str) {
        if (str.contains("[e]")) {
            str = str.replaceAll("\\[e\\]", ":");
        }
        if (str.contains("[/e]")) {
            str = str.replaceAll("\\[/e\\]", ":");
        }
        return str;
    }

    public static boolean isTablet(Context context) {
        return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;
    }


    /**
     * 判断是否为平板
     * 
     * @return
     */
    public static boolean isPad(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        // 屏幕宽度
        float screenWidth = display.getWidth();
        // 屏幕高度
        float screenHeight = display.getHeight();
        DisplayMetrics dm = new DisplayMetrics();
        display.getMetrics(dm);
        double x = Math.pow(dm.widthPixels / dm.xdpi, 2);
        double y = Math.pow(dm.heightPixels / dm.ydpi, 2);
        // 屏幕尺寸
        double screenInches = Math.sqrt(x + y);
        // 大于6尺寸则为Pad
        if (screenInches >= 6.0) {
            return true;
        }
        return false;
    }


    /**
     * 设置PopupWindow的全屏遮罩
     */
    public static void addScreenBg(PopupWindow popupWindow, final Activity context) {
        showScreenBg(context);
        popupWindow.setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss() {
                hiddenScreenBg(context);
            }
        });
    }

    /**
     * 显示全屏遮罩
     */
    public static void showScreenBg(Activity context) {
        final WindowManager.LayoutParams lp = context.getWindow().getAttributes();
        lp.alpha = 0.5f;
        context.getWindow().setAttributes(lp);
    }

    /**
     * 显示全屏遮罩
     */
    public static void hiddenScreenBg(Activity context) {
        WindowManager.LayoutParams lp = context.getWindow().getAttributes();
        lp.alpha = 1f;
        context.getWindow().setAttributes(lp);
    }


    public static void goZan(final Activity context, final Map<Integer, Boolean> isZanMap,
            final Map<Integer, ImageView> map, final int position,
            final MainZuixinData.MainTiezi value) {

        if (UserState.isLogged(context)) {
            if (isZanMap.get(position)) {
                Toast.makeText(context, "已赞过 !", Toast.LENGTH_SHORT).show();
            } else {
                if (CommonUtil.checkNetState(context)) {

                    map.get(position).setImageResource(R.drawable.icon_hand_frs_click);


                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {

                        final ObjectAnimator oa =
                                ObjectAnimator.ofInt(new ViewWrapper2(map.get(position)), "width",

                                CommonUtil.dip2px(context, 0), CommonUtil.dip2px(context, 40));
                        final ObjectAnimator ob =
                                ObjectAnimator.ofInt(new ViewWrapper2(map.get(position)), "height",

                                CommonUtil.dip2px(context, 0), CommonUtil.dip2px(context, 40));
                        oa.setInterpolator(new AccelerateDecelerateInterpolator());
                        ob.setInterpolator(new AccelerateDecelerateInterpolator());
                        oa.setDuration(250);
                        ob.setDuration(250);


                        final AnimatorSet set = new AnimatorSet();
                        set.play(oa).with(ob);

                        set.addListener(new AnimatorListener() {

                            @Override
                            public void onAnimationStart(Animator arg0) {

                            }

                            @Override
                            public void onAnimationRepeat(Animator arg0) {}

                            @Override
                            public void onAnimationEnd(Animator arg0) {

                                ObjectAnimator oa2 =
                                        ObjectAnimator.ofInt(new ViewWrapper2(map.get(position)),
                                                "width", CommonUtil.dip2px(context, 40),
                                                CommonUtil.dip2px(context, 25));
                                ObjectAnimator ob2 =
                                        ObjectAnimator.ofInt(new ViewWrapper2(map.get(position)),
                                                "height", CommonUtil.dip2px(context, 40),
                                                CommonUtil.dip2px(context, 25));
                                oa2.setInterpolator(new AccelerateDecelerateInterpolator());
                                ob2.setInterpolator(new AccelerateDecelerateInterpolator());
                                oa2.setDuration(250);
                                ob2.setDuration(250);

                                AnimatorSet set2 = new AnimatorSet();
                                set2.play(oa2).with(ob2);
                                set2.start();

                            }

                            @Override
                            public void onAnimationCancel(Animator arg0) {
                                // TODO Auto-generated method stub

                            }
                        });

                        set.start();
                    }


                    RequestParams params = new RequestParams();
                    params.put("tid", value.tid);
                    params.put("uid", UserState.getUserUid());
                    XDHttpClient.get(xdConfig.PRAISEPOST, params, new AsyncHttpResponseHandler() {
                        @Override
                        public void onSuccess(int statusCode, String content) {

                            try {
                                if (new JSONObject(content).getInt("result") == 0) {

                                    MainZuixinData.MainTiezi.RecommendPerson info =
                                            new MainZuixinData().new MainTiezi().new RecommendPerson();
                                    info.username = UserState.getUser().username;
                                    info.recommenduid = UserState.getUserUid();
                                    value.recommendarray.add(0, info);
                                    value.recommendmy = "1";
                                    value.recommend_add =
                                            String.valueOf(Integer.parseInt(value.recommend_add) + 1);
                                    isZanMap.put(position, true);
                                    Toast.makeText(context, "点赞成功", Toast.LENGTH_SHORT).show();
                                    // mAdapter.notifyDataSetChanged();
                                } else {
                                    map.get(position).setImageResource(
                                            R.drawable.icon_hand_frs_normal);
                                    Toast.makeText(context, "点赞失败", Toast.LENGTH_SHORT).show();
                                }
                            } catch (JSONException e1) {
                                e1.printStackTrace();
                            }
                        }

                        @Override
                        public void onFailure(Throwable arg0, String arg1) {
                            super.onFailure(arg0, arg1);
                            map.get(position).setImageResource(R.drawable.icon_hand_frs_normal);
                            Toast.makeText(context, R.string.get_error_data, Toast.LENGTH_SHORT)
                                    .show();
                        }
                    });
                } else {
                    Toast.makeText(context, R.string.pLease_check_network, Toast.LENGTH_SHORT)
                            .show();
                    return;
                }
            }
        }
    }


    /**
     * 显示引导页面
     */
    public static void showHelpPopupWindow(Activity context, int layoutId, int resId,
            View showAtLocation) {
        final HelpPopupWindow helpWindow = new HelpPopupWindow(context);
        View view = View.inflate(context, layoutId, null);
        ImageView iv_help = (ImageView) view.findViewById(R.id.iv_help);
        iv_help.setLayoutParams(new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                (int) ((float) CommonParameter.sScreenWidth * 1136 / 640)));

        final Bitmap decodeStream =
                BitmapFactory.decodeStream(context.getResources().openRawResource(resId));
        iv_help.setImageBitmap(decodeStream);
        view.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss(helpWindow, decodeStream);
            }
        });

        view.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_MOVE:
                        dismiss(helpWindow, decodeStream);
                        break;
                }
                return false;
            }
        });
        helpWindow.init(view).showAtLocation(showAtLocation, Gravity.CENTER, 0, 0);
    }

    private static void dismiss(PopupWindow helpWindow, Bitmap decodeStream) {
        helpWindow.dismiss();
        decodeStream.recycle();
        System.gc();
    }

    /**
     * 防止按钮重复被点击
     */
    private static long lastClickTime;

    public static boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        long timeD = time - lastClickTime;
        if (0 < timeD && timeD < 600) {
            return true;
        }
        lastClickTime = time;
        return false;
    }

    public static boolean isFastDoubleClick2() {
        long time = System.currentTimeMillis();
        long timeD = time - lastClickTime;
        if (0 < timeD && timeD < 2000) {
            return true;
        }
        lastClickTime = time;
        return false;
    }


    public static boolean isBackground(Context context) {
        ActivityManager activityManager =
                (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
        for (RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(context.getPackageName())) {
                if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_BACKGROUND) {
                    // Log.i("后台", appProcess.processName);
                    return true;
                } else {
                    // Log.i("前台", appProcess.processName);
                    return false;
                }
            }
        }
        return false;
    }

    public static void logoutQQ(Activity mContext) {
        HappyPetApplication.get().getUMController()
                .deleteOauth(mContext, SHARE_MEDIA.QQ, new SocializeClientListener() {
                    @Override
                    public void onStart() {}

                    @Override
                    public void onComplete(int status, SocializeEntity entity) {
                        if (status == 200) {
                            // Toast.makeText(mContext, "删除成功.", Toast.LENGTH_SHORT).show();
                        } else {
                            // Toast.makeText(mContext, "删除失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }



}
